#include "signalprocessor.h"

SignalProcessor::SignalProcessor(double fc, double fs, double T, double snr)
    : fc(fc), fs(fs), T(T), snr(snr)
{
    sigCh1 = generateSignal(0); // 通道1信号，初始相位偏差为0
    auto sigCh2 = generateSignal(20); // 通道2信号，初始相位偏差为20
    sigCh1.conservativeResize(sigCh1.size() + sigCh2.size());
    sigCh1.tail(sigCh2.size()) = sigCh2;
}
//生成正弦信号
RowVectorX<std::complex<double>> SignalProcessor::genSig(double fc, double fs, double phi_0, double pw, double snr, const std::string& type)
{
    QVector<double> t0 = linSpace(1 / fs, 0, T); // 时间向量
    RowVectorXd t1=QVectorToRowVectorXd(t0);


    RowVectorX<std::complex<double>> sig(t1.size()); // 初始化复数信号向量
    std::complex<double> j(0.0, 1.0); // 复数单位j

    if (type == "CW") {
        // 生成CW信号
        RowVectorXd t2 = 2 * M_PI * fc * t1.array() + phi_0; // 相位角度
        sig = (t2.array() * j).exp(); // 计算 e^(j*theta)

    } else if (type == "LFM") {
        // 生成LFM信号
        double k = pw; // 假设pw是调频率
        RowVectorXd squaredVec = 0.5 * k * t1.array().square(); // 二次相位项
        RowVectorXd tempCalcu = 2 * M_PI * (fc * t1 + squaredVec); // 总相位
        sig = (tempCalcu.array() * j).exp(); // 计算 e^(j*theta)
    }

    // 添加噪声
    //sig = addNoise(sig, snr);

    return sig;
}
RowVectorXd SignalProcessor::QVectorToRowVectorXd(const QVector<double>& qVector)
{
    // 创建与 QVector<double> 大小相同的 RowVectorXd
    Eigen::RowVectorXd rowVector(qVector.size());

    // 将 QVector<double> 的数据复制到 RowVectorXd
    for (int i = 0; i < qVector.size(); ++i) {
        rowVector(i) = qVector[i];
    }

    return rowVector;
}

RowVectorX<std::complex<double>> SignalProcessor::generateSignal(double phaseOffset)
{
    // 实现信号生成逻辑，例如LFM信号等
    // 此处假设genSig是某个生成信号的方法
    return genSig(fc, fs, phaseOffset, T, snr, "LFM");
}
QVector<double> SignalProcessor::linSpace(double step, double start, double end)
{
    // 计算生成的点的数量
    int size = static_cast<int>((end - start) / step) + 1;

    // 创建 QVector<double> 并填充数据
    QVector<double> rx(size);
    for (int i = 0; i < size; ++i) {
        rx[i] = start + i * step;
    }

    return rx;
}

QVector<double> SignalProcessor::generateSignalRealValues()
{
    QVector<double> realValues(sigCh1.size());
    for (int i = 0; i < sigCh1.size(); ++i) {
        realValues[i] = sigCh1(i).real();
    }
    return realValues;
}
QVector<double> SignalProcessor::generateSignalImagValues()
{
    QVector<double> imagValues(sigCh1.size());
    for (int i = 0; i < sigCh1.size(); ++i) {
        imagValues[i] = sigCh1(i).imag();
    }
    return imagValues;
}
